<template>
  <div class="order-analysis-page">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilterChange"
          />
        </el-form-item>
        <el-form-item label="销售员">
          <el-select v-model="filterForm.salesman" placeholder="全部" clearable @change="handleFilterChange">
            <el-option label="全部销售员" value="" />
            <el-option label="销售员A" value="销售员A" />
            <el-option label="销售员B" value="销售员B" />
            <el-option label="销售员C" value="销售员C" />
            <el-option label="销售员D" value="销售员D" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户分类">
          <el-select v-model="filterForm.customerType" placeholder="全部" clearable @change="handleFilterChange">
            <el-option label="全部客户" value="" />
            <el-option label="VIP客户" value="vip" />
            <el-option label="普通客户" value="normal" />
            <el-option label="新客户" value="new" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="filterForm.productCategory" placeholder="全部" clearable @change="handleFilterChange">
            <el-option label="全部产品" value="" />
            <el-option label="电子产品" value="electronics" />
            <el-option label="服装鞋帽" value="clothing" />
            <el-option label="家居用品" value="home" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 关键指标卡片 -->
    <el-row :gutter="20" class="metrics-row">
      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="订单总数" :value="metrics.totalOrders">
            <template #suffix>单</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.ordersTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.ordersTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.ordersTrend) }}%
            </span>
            <span class="trend-label">环比上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="订单总额" :value="metrics.totalAmount" :precision="2">
            <template #prefix>¥</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.amountTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.amountTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.amountTrend) }}%
            </span>
            <span class="trend-label">环比上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="平均客单价" :value="metrics.avgOrderAmount" :precision="2">
            <template #prefix>¥</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.avgTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.avgTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.avgTrend) }}%
            </span>
            <span class="trend-label">环比上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="客户总数" :value="metrics.totalCustomers">
            <template #suffix>人</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.customersTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.customersTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.customersTrend) }}%
            </span>
            <span class="trend-label">环比上期</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单趋势分析</span>
              <el-radio-group v-model="trendType" size="small" @change="loadTrendChart">
                <el-radio-button label="daily">按日</el-radio-button>
                <el-radio-button label="weekly">按周</el-radio-button>
                <el-radio-button label="monthly">按月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <span>订单来源分析</span>
          </template>
          <div ref="sourceChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>销售员业绩排行</span>
          </template>
          <div ref="salesmanChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <span>产品销售排行</span>
          </template>
          <div ref="productChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>区域销售分布</span>
          </template>
          <div ref="regionChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <span>订单时段分布</span>
          </template>
          <div ref="timeDistChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="mt-20">
      <template #header>
        <div class="card-header">
          <span>订单明细数据</span>
          <el-button type="primary" size="small" @click="handleExportDetail">
            <el-icon><Download /></el-icon>
            导出明细
          </el-button>
        </div>
      </template>

      <el-table :data="detailData" stripe v-loading="loading" max-height="400">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="orderCount" label="订单数" width="100" />
        <el-table-column prop="orderAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.orderAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="newCustomers" label="新客户数" width="100" />
        <el-table-column prop="repeatCustomers" label="复购客户数" width="120" />
        <el-table-column prop="avgAmount" label="平均客单价" width="120">
          <template #default="{ row }">
            ¥{{ row.avgAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="conversionRate" label="转化率" width="100">
          <template #default="{ row }">
            {{ row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="returnRate" label="退货率" width="100">
          <template #default="{ row }">
            {{ row.returnRate }}%
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 同比环比分析 -->
    <el-card class="mt-20">
      <template #header>
        <span>同比环比分析</span>
      </template>
      <el-table :data="comparisonData" border>
        <el-table-column prop="metric" label="指标" width="150" />
        <el-table-column prop="current" label="当期" width="150" />
        <el-table-column prop="lastPeriod" label="环比上期" width="150" />
        <el-table-column label="环比增长" width="150">
          <template #default="{ row }">
            <span :class="['comparison-value', row.periodGrowth > 0 ? 'positive' : 'negative']">
              {{ row.periodGrowth > 0 ? '+' : '' }}{{ row.periodGrowth }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastYear" label="同比去年" width="150" />
        <el-table-column label="同比增长" width="150">
          <template #default="{ row }">
            <span :class="['comparison-value', row.yearGrowth > 0 ? 'positive' : 'negative']">
              {{ row.yearGrowth > 0 ? '+' : '' }}{{ row.yearGrowth }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="趋势图" width="200">
          <template #default="{ row }">
            <div class="trend-chart">
              <div 
                v-for="(value, index) in row.trendData" 
                :key="index"
                class="trend-bar"
                :style="{ height: value + '%' }"
              ></div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { Download, CaretTop, CaretBottom } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const trendType = ref('daily')
const trendChartRef = ref(null)
const sourceChartRef = ref(null)
const salesmanChartRef = ref(null)
const productChartRef = ref(null)
const regionChartRef = ref(null)
const timeDistChartRef = ref(null)

let trendChart = null
let sourceChart = null
let salesmanChart = null
let productChart = null
let regionChart = null
let timeDistChart = null

// 筛选条件
const filterForm = reactive({
  dateRange: [],
  salesman: '',
  customerType: '',
  productCategory: ''
})

// 关键指标
const metrics = reactive({
  totalOrders: 1248,
  ordersTrend: 12.5,
  totalAmount: 3856240.50,
  amountTrend: 8.3,
  avgOrderAmount: 3090.22,
  avgTrend: -2.1,
  totalCustomers: 856,
  customersTrend: 15.8
})

// 详细数据
const detailData = ref([
  {
    date: '2024-01-15',
    orderCount: 45,
    orderAmount: 135000,
    newCustomers: 12,
    repeatCustomers: 33,
    avgAmount: 3000,
    conversionRate: 8.5,
    returnRate: 1.2
  },
  {
    date: '2024-01-14',
    orderCount: 52,
    orderAmount: 158000,
    newCustomers: 15,
    repeatCustomers: 37,
    avgAmount: 3038,
    conversionRate: 9.2,
    returnRate: 0.8
  },
  {
    date: '2024-01-13',
    orderCount: 38,
    orderAmount: 112000,
    newCustomers: 8,
    repeatCustomers: 30,
    avgAmount: 2947,
    conversionRate: 7.8,
    returnRate: 1.5
  }
])

// 同比环比数据
const comparisonData = ref([
  {
    metric: '订单数',
    current: '1,248',
    lastPeriod: '1,110',
    periodGrowth: 12.4,
    lastYear: '980',
    yearGrowth: 27.3,
    trendData: [60, 65, 70, 75, 80, 85, 90, 95]
  },
  {
    metric: '订单金额',
    current: '¥385.62万',
    lastPeriod: '¥356.12万',
    periodGrowth: 8.3,
    lastYear: '¥298.45万',
    yearGrowth: 29.2,
    trendData: [55, 60, 65, 72, 78, 82, 88, 92]
  },
  {
    metric: '客单价',
    current: '¥3,090',
    lastPeriod: '¥3,157',
    periodGrowth: -2.1,
    lastYear: '¥3,045',
    yearGrowth: 1.5,
    trendData: [85, 82, 80, 78, 75, 72, 70, 68]
  },
  {
    metric: '新客户数',
    current: '256',
    lastPeriod: '221',
    periodGrowth: 15.8,
    lastYear: '189',
    yearGrowth: 35.4,
    trendData: [50, 55, 62, 68, 75, 82, 88, 95]
  }
])

// 方法
const handleFilterChange = () => {
  ElMessage.info('正在重新加载数据...')
  loadAllCharts()
}

const handleExport = () => {
  ElMessage.success('正在导出报表...')
}

const handleExportDetail = () => {
  ElMessage.success('正在导出明细数据...')
}

const handleViewDetail = (row) => {
  ElMessage.info(`查看 ${row.date} 的详细数据`)
}

// 初始化订单趋势图表
const loadTrendChart = () => {
  if (!trendChartRef.value) return
  
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dataMap = {
    daily: {
      categories: ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日'],
      orders: [120, 132, 101, 134, 90, 230, 210, 185, 195, 205, 220, 215, 238, 252, 245],
      amounts: [360000, 396000, 303000, 402000, 270000, 690000, 630000, 555000, 585000, 615000, 660000, 645000, 714000, 756000, 735000]
    },
    weekly: {
      categories: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周'],
      orders: [750, 820, 780, 890, 920, 880],
      amounts: [2250000, 2460000, 2340000, 2670000, 2760000, 2640000]
    },
    monthly: {
      categories: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      orders: [3520, 3200, 3800, 4200, 3900, 4500, 4800, 4600, 5000, 5200, 4900, 5500],
      amounts: [10560000, 9600000, 11400000, 12600000, 11700000, 13500000, 14400000, 13800000, 15000000, 15600000, 14700000, 16500000]
    }
  }

  const data = dataMap[trendType.value]

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['订单数', '订单金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.categories
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数',
        position: 'left'
      },
      {
        type: 'value',
        name: '金额(元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        data: data.orders,
        itemStyle: {
          color: '#5470c6'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ])
        }
      },
      {
        name: '订单金额',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: data.amounts,
        itemStyle: {
          color: '#91cc75'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        }
      }
    ]
  }

  trendChart.setOption(option)
}

// 初始化订单来源图表
const initSourceChart = () => {
  if (!sourceChartRef.value) return
  
  sourceChart = echarts.init(sourceChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 450, name: '线上商城', itemStyle: { color: '#5470c6' } },
          { value: 280, name: '线下门店', itemStyle: { color: '#91cc75' } },
          { value: 220, name: '电话订购', itemStyle: { color: '#fac858' } },
          { value: 180, name: '企业采购', itemStyle: { color: '#ee6666' } },
          { value: 118, name: '其他渠道', itemStyle: { color: '#73c0de' } }
        ]
      }
    ]
  }

  sourceChart.setOption(option)
}

// 初始化销售员业绩图表
const initSalesmanChart = () => {
  if (!salesmanChartRef.value) return
  
  salesmanChart = echarts.init(salesmanChartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: ['销售员E', '销售员D', '销售员C', '销售员B', '销售员A']
    },
    series: [
      {
        name: '订单金额',
        type: 'bar',
        data: [520000, 680000, 750000, 850000, 980000],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#667eea' },
            { offset: 1, color: '#764ba2' }
          ])
        },
        barWidth: '60%',
        label: {
          show: true,
          position: 'right',
          formatter: '¥{c}'
        }
      }
    ]
  }

  salesmanChart.setOption(option)
}

// 初始化产品销售图表
const initProductChart = () => {
  if (!productChartRef.value) return
  
  productChart = echarts.init(productChartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['产品J', '产品I', '产品H', '产品G', '产品F', '产品E', '产品D', '产品C', '产品B', '产品A']
    },
    series: [
      {
        name: '销售数量',
        type: 'bar',
        data: [125, 156, 178, 195, 218, 245, 268, 295, 325, 358],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: '#00f2fe' }
          ])
        }
      }
    ]
  }

  productChart.setOption(option)
}

// 初始化区域分布图表
const initRegionChart = () => {
  if (!regionChartRef.value) return
  
  regionChart = echarts.init(regionChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '70%',
        data: [
          { value: 320, name: '华北', itemStyle: { color: '#5470c6' } },
          { value: 280, name: '华东', itemStyle: { color: '#91cc75' } },
          { value: 220, name: '华南', itemStyle: { color: '#fac858' } },
          { value: 180, name: '西南', itemStyle: { color: '#ee6666' } },
          { value: 150, name: '东北', itemStyle: { color: '#73c0de' } },
          { value: 98, name: '西北', itemStyle: { color: '#3ba272' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  regionChart.setOption(option)
}

// 初始化时段分布图表
const initTimeDistChart = () => {
  if (!timeDistChartRef.value) return
  
  timeDistChart = echarts.init(timeDistChartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['0-2时', '2-4时', '4-6时', '6-8时', '8-10时', '10-12时', '12-14时', '14-16时', '16-18时', '18-20时', '20-22时', '22-24时']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        type: 'bar',
        data: [12, 8, 15, 45, 125, 156, 142, 168, 195, 158, 98, 52],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: '#43e97b' },
            { offset: 1, color: '#38f9d7' }
          ])
        }
      }
    ]
  }

  timeDistChart.setOption(option)
}

// 加载所有图表
const loadAllCharts = () => {
  loadTrendChart()
  initSourceChart()
  initSalesmanChart()
  initProductChart()
  initRegionChart()
  initTimeDistChart()
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  trendChart?.resize()
  sourceChart?.resize()
  salesmanChart?.resize()
  productChart?.resize()
  regionChart?.resize()
  timeDistChart?.resize()
}

// 生命周期
onMounted(() => {
  setTimeout(() => {
    loadAllCharts()
    window.addEventListener('resize', handleResize)
  }, 100)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  sourceChart?.dispose()
  salesmanChart?.dispose()
  productChart?.dispose()
  regionChart?.dispose()
  timeDistChart?.dispose()
})
</script>

<style scoped>
.order-analysis-page {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
}

.metrics-row {
  margin-bottom: 20px;
}

.metric-card {
  padding: 8px;
}

.metric-trend {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 600;
}

.trend.up {
  color: #67c23a;
}

.trend.down {
  color: #f56c6c;
}

.trend-label {
  font-size: 12px;
  color: #909399;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.comparison-value {
  font-weight: bold;
}

.comparison-value.positive {
  color: #67c23a;
}

.comparison-value.negative {
  color: #f56c6c;
}

.trend-chart {
  display: flex;
  align-items: flex-end;
  height: 40px;
  gap: 4px;
}

.trend-bar {
  flex: 1;
  background: linear-gradient(to top, #409EFF, #a0cfff);
  border-radius: 2px;
  min-height: 5px;
}
</style>

